const _ = require('lodash');
const Promise = require('bluebird');

/**
 * @api {get} /api/public/v1/app/menu 后台管理菜单
 */
exports.menu = function ({query, user_id}, {models: {Users, Permissions}, cache: {settings}, paths}) {
    return Users.findOne({
        where: {id: user_id},
        attributes: ['id', 'tel', 'username', 'nickname', 'email', 'level', 'role', 'status', 'created_at']
    }).then(function (user) {
        if (!user) {
            return {message: '用户未登录', code: 401};
        }
        if (user.role == 'SuperAdmin') {
            let menus_admin = require(paths.json + 'menus_web_admin.json');
            return Permissions.findAllByUserV2({user_id: user_id}).then(function (permissions) {
                let admin_menus = [];
                if (permissions.length) {
                    let map = {};
                    for (let i in permissions) {
                        let permission = permissions[i];
                        map[permission.object_type + '-' + permission.action_type] = true;
                    }

                    for (let i in menus_admin) {
                        let menu = _.cloneDeep(menus_admin[i]);
                        let keys = i.split('||');
                        for (let j in keys) {
                            let key = keys[j];
                            if (map[key]) {
                                admin_menus.push(menu);
                                break;
                            }
                        }
                        if (menu.sub_menus) {
                            let subMenus = [];
                            for (let j in menu.sub_menus) {
                                if (map[j.split('||')[0]]) {
                                    subMenus.push(menu.sub_menus[j]);
                                }
                            }
                            menu.sub_menus = subMenus;
                        }
                    }
                }
                return {
                    user: user,
                    menus: [{text: '管理员菜单', menus: admin_menus}],
                    admin_title: settings.value('admin_title')
                };
            });
        }
        return {message: '没有权限访问后台'};
    });
};

/**
 * @api {get} /api/public/v1/app/wechat_js_config 后台管理菜单
 */
exports.wechatJsConfig = function ({query}, {wechatInstance, config}) {
    let {url} = query;
    return new Promise(function (resolve) {
        let wechat_jssdk = Object.assign(config.wechat_jssdk, {url: url});
        wechatInstance.shopWebApi.getJsConfig(wechat_jssdk, function (err, result) {
            if (err) {
                console.error('\n', err.stack || err.message);
                return resolve({success: false});
            }
            return resolve({success: true, data: result});
        });
    });
};